package com.zzyl.nursing.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class TimeUtil {

    // 定义输入的时间格式
    private static final DateTimeFormatter CUSTOM_UTC_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");

    public static LocalDateTime transform(String time) {
        if (StringUtils.isEmpty(time)) {
            return null;
        }

        LocalDateTime activeTime;
        try {
            // 首先尝试使用Hutool的默认UTC_MS_PATTERN解析
            activeTime = LocalDateTimeUtil.parse(time, DatePattern.UTC_MS_PATTERN);
        } catch (Exception e) {
            // 如果失败，尝试使用自定义格式解析
            try {
                activeTime = LocalDateTime.parse(time, CUSTOM_UTC_FORMAT);
            } catch (Exception ex) {
                // 如果两种格式都失败，抛出异常
                throw new RuntimeException("无法解析时间字符串: " + time, ex);
            }
        }

        // 日期时区转换
        activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        return activeTime;
    }
}